package com.szgd.controller.equipment;

import com.szgd.controller.BaseController;
import com.szgd.service.equipment.EquipWorkService;
import com.szgd.service.equipment.EquipmentService;
import com.szgd.service.personnel.AttachService;
import com.szgd.util.Constant;
import com.szgd.util.ExcelUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.TimeUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/equipmentInfo")
public class EquipmentController extends BaseController {
    private static Logger logger = Logger.getLogger(EquipmentController.class);

    @Autowired
    EquipmentService equipmentService;
    @Autowired
    AttachService attachService;
    @Autowired
    EquipWorkService equipWorkService;

    //***************跳转设备基础信息页面********************//
    @RequestMapping(value = "toEquipmentInfoList", method = RequestMethod.GET)
    public String toEquipmentInfoList() {
        return "/equipment/equipmentInfo/equipmentInfoList";
    }

    //***************跳转设备查看页面********************//
    @RequestMapping(value = "toEquipmentInfoView", method = RequestMethod.GET)
    public ModelAndView toEquipmentInfoView(HttpServletRequest request, HttpSession session) {
        ModelAndView mv = getModelAndView(request,session,"/equipment/equipmentInfo/equipmentInfoView");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");
        if (id.length() > 0) {
            Map<String, Object> equipMap = equipmentService.getEquipment(id);
            mv.addObject("equip",equipMap);
        }
        return mv;
    }

    //***************跳转设备编辑/新增页面********************//
    @RequestMapping(value = "toEquipmentInfoForm", method = RequestMethod.GET)
    public ModelAndView toEquipmentInfoForm(HttpServletRequest request, HttpSession session) {
        ModelAndView mv = getModelAndView(request,session,"/equipment/equipmentInfo/equipmentInfoForm");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");;
        if (id.length() > 0) {
            Map<String, Object> equipMap = equipmentService.getEquipment(id);
            mv.addObject("equip",equipMap);
        }
        return mv;
    }

    //***************根据条件查询设备信息********************//
    @RequestMapping(value = "/getEquipmentInfoListNoPage")
    @ResponseBody
    public  Map<String, Object>  getEquipmentInfoListNoPage(@RequestBody HashMap<String, Object> paramMap,HttpServletResponse response,HttpServletRequest request){
        List<Map<String, Object>> dataList = equipmentService.getEquipmentInfoListNoPage(paramMap);
        return getSuccMap(dataList);
    }

    //***************获取设备信息列表********************//
    @RequestMapping(value = "/getEquipmentInfoList", method = RequestMethod.GET)
    public void  getEquipmentInfoList(HttpServletResponse response,HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        List<Map<String, Object>> dataList = equipmentService.getEquipmentInfoList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    //***************删除设备********************//
    @RequestMapping(value = "/delEquipmentInfo")
    @ResponseBody
    public Map<String,Object> delEquipmentInfo(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        try{
            paramMap.put("uploader",this.getLoginId(request.getSession()));
            equipmentService.deleteEquipment(paramMap);

            String message = "设备信息删除成功！";
            return getSuccMap(message);
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("设备信息删除失败："+e.getMessage());
            return getSuccMap("设备信息删除失败："+e.getMessage());
        }
    }

    //***************编辑/新增设备信息********************//
    @RequestMapping(value = "/saveEquipInfo")
    @ResponseBody
    public Map<String,Object> saveEquipInfo(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request,HttpServletResponse response) {
        String id = paramMap.get("id")== null?"":paramMap.get("id").toString().replace("null","");
        String message;
        try {
            if (id.length() == 0){//新增
                if (equipmentService.getEquipmentCount(paramMap) > 0)
                {
                    message = "设备信息表里已经存在相同的设备编号!";
                    return getErrorMap(message);
                }
                paramMap.put("creator",this.getLoginId(request.getSession()));
                equipmentService.insertEquipment(paramMap);
            } else {
                paramMap.put("uploader",this.getLoginId(request.getSession()));
                equipmentService.updateEquipment(paramMap);
            }
            message = "设备信息保存成功!";
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("设备信息保存失败："+e.getMessage());
            return getErrorMap("设备信息保存失败："+e.getMessage());
        }
    }

    //***************excel批量导入设备信息********************//
    @ResponseBody
    @RequestMapping(value = "/batchUploadEquipmentInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public void batchUploadEquipmentInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in;
        MultipartFile file = multipartRequest.getFile("file");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        PrintWriter out;
        response.setCharacterEncoding("UTF-8");  //防止ajax接受到的中文信息乱码
        response.setHeader("Content-type", "text/html;charset=UTF-8");   //跟上面同时使用可解决乱码问题
        out = response.getWriter();
        try {
            Map<String, String> fieldMapping = equipmentService.getFieldMap();
            List<Map<String, Object>> dataList = ExcelUtil.getListByExcel(in, file.getOriginalFilename(), fieldMapping, false);
            String batchNo = TimeUtil.formatDate(Calendar.getInstance().getTime(), "yyyyMMddhhmmss");
            Map<String, Object> resultMap = equipmentService.batchImportEquipInfo(dataList, this.getLoginId(request.getSession()), batchNo);

            long endTime = System.currentTimeMillis();
            List<Map<String, Object>> successList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_SUCCESS);
            List<Map<String, Object>> failedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_FAILED);
            List<Map<String, Object>> updatedList = (List<Map<String, Object>>) resultMap.get(Constant.IMPORT_HE_UPDATED);
            String errorHtml = failedList.size() + "条";

            if (failedList.size() > 0) {
                //生成失败记录文件
                String fileName = "设备列表" + batchNo + ".xls";
                String filePath = PropertiesUtil.get("batchImportErrorPath");
                String realPath = request.getServletContext().getRealPath(filePath);
                filePath = filePath.replace("\\", "/");
                File f = new File(realPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                realPath = realPath + File.separator + fileName;
                exportExcelByTemplate(fieldMapping,failedList, realPath,"设备信息批量导入模版.xls");
                String downloadPath = filePath + "/" + URLEncoder.encode(fileName,"UTF-8");
                errorHtml = "<a href='#WEBROOT#/downloadErrorRecord?path=" + downloadPath + "'>" + failedList.size() + "条（点击查看失败原因）</a>";
            }
            out.print("本次导入共处理" + dataList.size() + "条数据[新增：" + successList.size() + "条，更新："
                    + updatedList.size() + "条，<font color='red'>失败：" + errorHtml
                    + "</font>]，耗时： "
                    + (endTime - startTime) / 1000 + "秒！");
        } catch (Exception e) {
            out.print("文件导入失败！");
            logger.error(e.getMessage());
        }
        out.flush();
        out.close();
    }

    /***********下载设备信息*********/
    @ResponseBody
    @RequestMapping(value = "/downloadEquipInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadEquipInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> fieldMapping = equipmentService.getLogMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd") ;
        String fileName = "设备信息" + sdf.format(new Date()) + ".xls";
        String filePath = PropertiesUtil.get("downloadPath");
        String realPath = request.getServletContext().getRealPath(filePath);
        filePath = filePath.replace("\\", "/");
        File f = new File(realPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        realPath = realPath + File.separator + fileName;
        List<Map<String, Object>> dataList = equipmentService.getEquipmentExcel(null);
        exportExcelByTemplate(fieldMapping,dataList, realPath,"设备信息导出模板.xls");
        String downloadPath = filePath + "/" + fileName;
        realPath = request.getServletContext().getRealPath(downloadPath);
        try {
            this.download(response, realPath);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        new File(realPath).delete();
    }
}
